//
//  MYNetworkingTools.swift
//  Sina
//
//  Created by 王亮龙1 on 16/5/23.
//  Copyright © 2016年 lianglong. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethods: Int {
    case GET
    case POST
}


//API
struct API {
    
    static let hostName = "https://api.weibo.com/"
    //加载用户token
    static let loadAccessToken = "oauth2/access_token"
    //加载用户信息
    static let loadUserInfo = "2/users/show.json"
    //加载首页数据
    static let loadHomedata = "2/statuses/home_timeline.json"
    //发布微博
    static let sendStatus = "2/statuses/update.json"
    //发布图片微博
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"

}




class MYNetworkingTools: AFHTTPSessionManager {
    
    static let shareTools: MYNetworkingTools = {
        
        let baseUrl = NSURL(string: API.hostName)
        let tools = MYNetworkingTools(baseURL: baseUrl)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    
    
    func request(method:HTTPMethods, urlString: String, parameters: AnyObject?, finshed:(responseObject: AnyObject?, error: NSError?) -> () ) {
        
        let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> () in
            finshed(responseObject: result, error: nil)
        }
        
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> () in
            finshed(responseObject: nil, error: error)
        }
        
        if method == .GET {
            
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
}


//MARK:用户认证, 获取用户信息的方法
extension MYNetworkingTools {
    
    func loadAccountToken(code: String, finshed:(responseObject: AnyObject?, error: NSError?) -> ()) {
        
        let parameters = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : grant_type, "code" : code, "redirect_uri" : redirect_uri];
        
        
        request(.POST, urlString: API.loadAccessToken, parameters: parameters, finshed: finshed)
        
        
        
    }
    
    //请求用户信息的方法
    func loadUserInfo(respone: [String : AnyObject], finshed:(responseObject: AnyObject?, error: NSError?) -> ()) {
        
        
        let token = respone["access_token"]!
        let uid = respone["uid"]!
        
        //字典中不能放nil,所以上边要强制解包
        let parameters = ["access_token": token, "uid": uid]
        
        
        
        request(.GET, urlString: API.loadUserInfo, parameters: parameters, finshed: finshed)
        
    }
    
    
}

//首页相关
extension MYNetworkingTools {
    
    func loadHomeData(since_id: Int64,max_id: Int64, finshed:(responseObject: AnyObject?, error: NSError?) -> ()) {
        
        guard let token = MYUserAccountViewModel.shareUserAccountViewModel.userAccount?.access_token else {
            return
        }
        
        var parameters = ["access_token" : token, "count" : "10"]
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        request(.GET, urlString: API.loadHomedata, parameters: parameters, finshed: finshed)
    }
    
}



//发布微博
extension MYNetworkingTools {
    
    func sendStatus(status: String, images: [UIImage], finshed:(responseObject: AnyObject?, error: NSError?) -> ()) {
        //确保token值存在
        guard let token = MYUserAccountViewModel.shareUserAccountViewModel.userAccount?.access_token else {
            return
        }
        
        let parameters = ["access_token" : token, "status" : status]
        
        if images.count > 0 {
            self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formata) in
                
                //遍历数组,把图片数组中的image转化成二进制数据formata
                for image in images {
                    let imageData = UIImagePNGRepresentation(image)!
                    //pic服务器接收图片数据的key值
                    formata.appendPartWithFileData(imageData, name: "pic",
                        //application/octet-stream: 编码方式,这个方式,表示忽略方式,需要用标准的,上网查
                        fileName: "mengduo", mimeType: "application/octet-stream")
                }
                
                }, progress: nil, success: { (_, result) in
                    
                    finshed(responseObject: result, error:nil)
                    
                }, failure: { (_, error) in
                    
                    finshed(responseObject: nil, error: error)
                    
            })
        } else {
            
            request(.POST, urlString: API.sendStatus, parameters: parameters, finshed: finshed)
        }
    }
    
    
    
    
}
    
    
    

